package com.uenpay.im.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qyx.android.weight.view.MyGridView;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.OaWebViewActivity;
import com.uenpay.im.ui.old.activity.attendance.ShakeSignActivity;
import com.uenpay.im.ui.old.activity.company.AllCompanyListActivity;
import com.uenpay.im.ui.old.activity.company.CompanyEntity;
import com.uenpay.im.ui.old.activity.dynamic.DynamicActivity;
import com.uenpay.im.ui.old.activity.group.MyGroupsActivity;
import com.uenpay.im.ui.old.activity.nearby.NearByPeopelActivity;
import com.uenpay.im.ui.old.activity.oa.AppEntity;
import com.uenpay.im.ui.old.activity.oa.AppGroupEntity;
import com.uenpay.im.ui.old.activity.oa.OaModuleAdapter;
import com.uenpay.im.ui.old.activity.publicnumber.MyPublicNumberListActivity;
import com.uenpay.im.ui.old.activity.wallet.ChargeActivity;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.entities.RotateImageViewEntity;
import com.uenpay.im.menu.MenuAdapter;
import com.uenpay.im.menu.MenuEntity;
import com.uenpay.im.menu.MenusHandle;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.MyViewPage;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Class Explain: 应用
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */

public class ApplyFragment extends Fragment {

    private int entid;
    private View view;
    private View loading;

    private UnredaMsgReceiver msgReceiver;
    private LinearLayout blan_layout;
//        private OaHandle mOaHandle;
    private ArrayList<RotateImageViewEntity> _list = new ArrayList<RotateImageViewEntity>();
    private LinearLayout menus_layout;
    private MenuAdapter mAdapter = null;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_apply_layout, container,
                    false);
            initView();
            initLisenter();
            getMenus();
//			getOaData();
            getBlan();
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        return view;
    }

    private void initView() {
//        mOaHandle = new OaHandle();
        view.findViewById(R.id.title_right_iv_layout).setVisibility(
                View.VISIBLE);
        loading = view.findViewById(R.id.loading);
        ((ImageView) view.findViewById(R.id.title_right_iv))
                .setImageResource(R.drawable.icon_choose_company);
        ((TextView) view.findViewById(R.id.title_textview))
                .setText(getResources().getString(R.string.apply));
        view.findViewById(R.id.back_layout).setVisibility(View.GONE);
        menus_layout = (LinearLayout) view.findViewById(R.id.menus_layout);
        blan_layout = (LinearLayout) view.findViewById(R.id.blan_layout);
        String companyName = IMApplication.config.getSelectedCompany();
        if (!TextUtils.isEmpty(companyName)) {
            ((TextView) view.findViewById(R.id.title_textview))
                    .setText(companyName);
        }
        entid = IMApplication.config.getSelectedCompanyId();
    }

    private void initLisenter() {
        view.findViewById(R.id.title_right_iv_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(getActivity(),
                                AllCompanyListActivity.class);
                        intent.putExtra("choose_company", true);
                        intent.putExtra("entid", entid);
                        startActivityForResult(intent, 100);
                    }
                });

    }

    @Override
    public void onResume() {
        if (msgReceiver == null) {
            msgReceiver = new UnredaMsgReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(BroadcastAction.DISCOVER_UNREAD_COUNT_ACTION);
            getActivity().registerReceiver(msgReceiver, filter);
        }
        setDynamicMsg();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        if (msgReceiver != null) {
            getActivity().unregisterReceiver(msgReceiver);
        }
        super.onDestroy();
    }

    public class UnredaMsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    BroadcastAction.DISCOVER_UNREAD_COUNT_ACTION)) {
                setDynamicMsg();
            }
        }
    }

//	private void getOaData() {
//		loading.setVisibility(View.VISIBLE);
//		mOaHandle.getOaData(entid, new OaHandle.IGetOaDataResultListener() {
//
//			@Override
//			public void onDataResult(int status, String msg,
//					ArrayList<AppGroupEntity> msg_list) {
//				loading.setVisibility(View.GONE);
//				if (status == HttpInvokeResultCode.RESULT_OK) {
//					oa_layout.removeAllViews();
//					if (msg_list != null && msg_list.size() > 0) {
//						for (int i = 0, size = msg_list.size(); i < size; i++) {
//							oa_layout.addView(getOaView(msg_list.get(i)));
//						}
//					}
//				} else if (!TextUtils.isEmpty(msg)) {
//					IMApplication.showToast(msg);
//				}
//			}
//		});
//	}

    private void getBlan() {
        RotateImageViewEntity mRotateImageViewEntity = new RotateImageViewEntity();
        mRotateImageViewEntity.resorce_pic_id = R.drawable.icon_bl;
        RotateImageViewEntity mRotateImageViewEntity1 = new RotateImageViewEntity();
        mRotateImageViewEntity1.resorce_pic_id = R.drawable.icon_bl;
        RotateImageViewEntity mRotateImageViewEntity2 = new RotateImageViewEntity();
        mRotateImageViewEntity2.resorce_pic_id = R.drawable.icon_bl;
        ArrayList<RotateImageViewEntity> arrayList = new ArrayList<>();
        arrayList.add(mRotateImageViewEntity);
        arrayList.add(mRotateImageViewEntity1);
        arrayList.add(mRotateImageViewEntity2);
        _list = arrayList;
        blan_layout.setVisibility(View.VISIBLE);
        myHandler.sendEmptyMessage(0);
//        mOaHandle.getBlan(new OaHandle.IGetBlanResultListner() {
//
//            @Override
//            public void onGetBlanResult(int status, String msg,
//                                        ArrayList<RotateImageViewEntity> msg_list) {
//                if (msg_list != null && msg_list.size() > 0) {
//                    _list = msg_list;
//                    blan_layout.setVisibility(View.VISIBLE);
//                    myHandler.sendEmptyMessage(0);
//                } else {
//                    blan_layout.setVisibility(View.GONE);
//                }
//            }
//        });
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message arg0) {
            if (arg0.what == 0) {
                MyViewPage myViewPage = new MyViewPage(getActivity(), _list,
                        R.color.transparent, new MyViewPage.IRotaryPhotoListener() {

                    @Override
                    public void onClicked(
                            RotateImageViewEntity rotateEntity,
                            int index) {
                        if (rotateEntity != null
                                && !TextUtils
                                .isEmpty(rotateEntity.web_url)) {
                            Intent intent = new Intent(getActivity(),
                                    OaWebViewActivity.class);
                            intent.putExtra("url", rotateEntity.web_url);
                            startActivity(intent);
                        }
                    }
                });
                blan_layout.addView(myViewPage.getView());
            }
            return false;
        }
    });

    /**
     *
     */
    private void setDynamicMsg() {
        // TODO: 2016/11/25 优化本地刷新
        getMenus();
//        if (mAdapter != null)
//            mAdapter.notifyDataSetChanged();
//        String custid = IMApplication.config.getDynamicLastSendCustId();
//        int count = IMApplication.config.getDynamicUnreadMsgCount();
//        if (!TextUtils.isEmpty(custid)) {
//            new_msg_avatar.SetUrl(APIConfiguration.getAvatarUrlNormal(custid,
//                    PacketType.PERSONAL), true);
//            new_dynamic_iv.setVisibility(View.VISIBLE);
//        } else {
//            new_msg_avatar.setImageResource(R.drawable.icon_dynamic);
//            new_dynamic_iv.setVisibility(View.GONE);
//        }
//
//        if (count < 1) {
//            unread_dynamic_count_tv.setVisibility(View.INVISIBLE);
//        } else {
//            if (count <= 99) {
//                unread_dynamic_count_tv.setText(count + "");
//            } else {
//                unread_dynamic_count_tv.setText("99+");
//            }
//            new_dynamic_iv.setVisibility(View.GONE);
//            unread_dynamic_count_tv.setVisibility(View.VISIBLE);
//        }

    }

    private void showNoCompanyDialog() {
        DialogUtility.showDialog(getActivity(), R.string.not_choose_company,
                R.string.sure, R.string.cancel, true,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        Intent intent = new Intent(getActivity(),
                                AllCompanyListActivity.class);
                        intent.putExtra("choose_company", true);
                        intent.putExtra("entid", entid);
                        startActivityForResult(intent, 100);
                    }
                });
    }

    private View getOaView(AppGroupEntity appGroupEntity) {
        View oaView = LayoutInflater.from(getActivity()).inflate(
                R.layout.item_office_layout, null);
        TextView oa_type_tv = (TextView) oaView.findViewById(R.id.oa_type_tv);
        MyGridView oa_gridview = (MyGridView) oaView
                .findViewById(R.id.oa_gridview);
        oa_type_tv.setText(appGroupEntity.groupname);
        OaModuleAdapter adapter = new OaModuleAdapter(getActivity(),
                appGroupEntity.arrayList);
        oa_gridview.setAdapter(adapter);
        oa_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (entid == 0) {
                    showNoCompanyDialog();
                } else {
                    AppEntity mAppEntity = (AppEntity) arg0.getAdapter()
                            .getItem(arg2);
                    if (mAppEntity != null) {
                        Intent intent = new Intent();
                        if (mAppEntity.type == 1) {
                            intent.setClass(getActivity(),
                                    OaWebViewActivity.class);
                            Log.e("logo地址：", mAppEntity.url);
                            intent.putExtra("url", mAppEntity.url);
                            intent.putExtra("entid", entid);
                        } else if (mAppEntity.type == 2) {
                            intent.setClass(getActivity(),
                                    ShakeSignActivity.class);
                            intent.putExtra("entid", entid);
                        }
                        startActivity(intent);
                    }
                }
            }

        });
        return oaView;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == Activity.RESULT_OK
                && data != null) {
            CompanyEntity mCompanyEntity = (CompanyEntity) data
                    .getSerializableExtra("mCompanyEntity");

            if (mCompanyEntity != null) {
                if (entid == mCompanyEntity.entid) {
                    return;
                }
                entid = mCompanyEntity.entid;
                IMApplication.config
                        .setSelectedCompany(mCompanyEntity.entname);
                IMApplication.config
                        .setSelectedCompanyId(mCompanyEntity.entid);
                ((TextView) view.findViewById(R.id.title_textview))
                        .setText(mCompanyEntity.entname);
//                getOaData();
                getMenus();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void getMenus() {
        MenusHandle.getMenus(new MenusHandle.IGetMenus() {
            @Override
            public void onResult(ArrayList<MenuEntity> arrayList) {
                menus_layout.removeAllViews();
                for (int i = 0, size = arrayList.size(); i < size; i++) {
                    View view = getMenuView(arrayList.get(i).name, arrayList.get(i).childrens);
                    menus_layout.addView(view);
                }
            }
        });
    }

    private View getMenuView(String name, ArrayList<MenuEntity> arrayList) {
        View menuView = View.inflate(getActivity(), R.layout.item_home_menu_layout, null);
        TextView type_name_tv = (TextView) menuView.findViewById(R.id.type_name_tv);
        type_name_tv.setText(name);
        MyGridView menu_gridview = (MyGridView) menuView.findViewById(R.id.menu_gridview);
        mAdapter = new MenuAdapter(getActivity(), arrayList);
        menu_gridview.setAdapter(mAdapter);
        menu_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MenuEntity menuEntity = (MenuEntity) parent.getAdapter().getItem(position);
                if (menuEntity != null) {
                    if (!TextUtils.isEmpty(menuEntity.json)) {
                        try {
                            JSONObject json = new JSONObject(menuEntity.json);
                            if (json.has("url")) {
                                String url = json.optString("url");
                                if (url.startsWith("http")) {
                                    Intent intent = new Intent(getActivity(), OaWebViewActivity.class);
                                    intent.putExtra("url", url);
                                    startActivity(intent);
                                } else if (url.startsWith("qyx://")) {
                                    processData(url);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        });
        return menuView;
    }
    /**
     * 用户点击的本地跳转处理
     *
     * @param url
     */
    private void processData(String url) {
        String tempStr = url.replace("qyx://", "");
        if (tempStr.indexOf("/") > -1) {
            String[] strArr = tempStr.split("/");
            String function = "";
            if (strArr.length >= 2) {
                function = strArr[1];
            }
            if (strArr.length > 0) {
                String typeNode = strArr[0];
                if (typeNode.equals("alert")) {
                    String content = url.substring(url.lastIndexOf("/") + 1, url.length());
                    DialogUtility.showSingleBtnDialog(getActivity(), content, R.string.sure, true, new IOnBottomDialogListener() {
                        @Override
                        public void onClicked() {
                        }
                    });
                    return;
                } else if (typeNode.equals("group")) {
                    Intent intent = new Intent(getActivity(), MyGroupsActivity.class);
                    startActivity(intent);
                } else if (typeNode.equals("near")) {
                    if (function.equals("index")) {
                        // TODO: 2016/11/15 找护士
                        Intent intent = new Intent(getActivity(), NearByPeopelActivity.class);
                        startActivity(intent);
                    }
                } else if (typeNode.equals("wallet")) {
                    if (function.equals("recharge")) {
                        // TODO: 2016/11/15 充值
                        Intent intent = new Intent(getActivity(), ChargeActivity.class);
                        startActivity(intent);
                    }
                } else if (typeNode.equals("chat")) {
                    if (function.equals("publicno")) {
                        // TODO: 2016/11/15 公众号
                        Intent intent = new Intent(getActivity(), MyPublicNumberListActivity.class);
                        startActivity(intent);
                    }
                } else if (typeNode.equals("monents")) {
                    if (function.equals("index")) {
                        // TODO: 2016/11/15 朋友圈
                        Intent intent = new Intent(getActivity(), DynamicActivity.class);
                        startActivity(intent);
                    }
                }
//                else if (typeNode.equals("contacts")) {
//                    if (function.equals("index")) {
//                        // TODO: 2016/11/15 通讯录
//                        Intent intent = new Intent(getActivity(), ContactsActivity.class);
//                        startActivity(intent);
//                    }
//                } else if (typeNode.equals("doctorqcode")) {
//                    if (function.equals("index")) {
//                        // TODO: 2017/1/6 医生二维码
//                        Intent intent = new Intent(getActivity(), DoctorQRActivity.class);
//                        startActivity(intent);
//                    }
//                }
            }
        }
    }

}
